<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;

/**
 * 图片管理
 *
 * @icon fa fa-image
 * @remark 管理报工图片和审核图片
 */
class ImageManager extends Backend
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 报工图片管理
     */
    public function reportImages()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = \app\admin\model\scanwork\ItemReportImage::with([
                'productItem.allocation.order', 
                'productItem.allocation.model.product', 
                'productItem.allocation.process', 
                'productItem.allocation.user',
                'uploadUser'
            ])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核图片管理
     */
    public function auditImages()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = \app\admin\model\scanwork\ItemAuditImage::with([
                'productItem.allocation.order', 
                'productItem.allocation.model.product', 
                'productItem.allocation.process', 
                'productItem.allocation.user',
                'uploadUser'
            ])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除报工图片
     */
    public function deleteReportImage($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = 'id';
            $list = \app\admin\model\scanwork\ItemReportImage::where($pk, 'in', $ids)->select();

            $count = 0;
            foreach ($list as $item) {
                try {
                    // 如果有云存储文件ID，删除云存储文件
                    if (!empty($item->cloud_file_id)) {
                        $cloudService = new \app\common\service\ScanworkCloudService();
                        $cloudService->deleteFile($item->cloud_file_id);
                    } else {
                        // 删除本地文件
                        @unlink(ROOT_PATH . 'public' . $item->image_url);
                    }
                    $count += $item->delete();
                } catch (Exception $e) {
                    // 记录错误但继续删除其他文件
                    error_log('删除报工图片失败：' . $e->getMessage());
                }
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 删除审核图片
     */
    public function deleteAuditImage($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = 'id';
            $list = \app\admin\model\scanwork\ItemAuditImage::where($pk, 'in', $ids)->select();

            $count = 0;
            foreach ($list as $item) {
                @unlink(ROOT_PATH . 'public' . $item->image_url);
                $count += $item->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 图片预览
     */
    public function preview($id, $type = 'report')
    {
        if ($type == 'report') {
            $image = \app\admin\model\scanwork\ItemReportImage::with([
                'productItem.allocation.order', 
                'productItem.allocation.model.product', 
                'productItem.allocation.process', 
                'productItem.allocation.user',
                'uploadUser'
            ])->find($id);
        } else {
            $image = \app\admin\model\scanwork\ItemAuditImage::with([
                'productItem.allocation.order', 
                'productItem.allocation.model.product', 
                'productItem.allocation.process', 
                'productItem.allocation.user',
                'uploadUser'
            ])->find($id);
        }
        
        if (!$image) {
            $this->error('图片不存在');
        }
        
        $this->view->assign('image', $image);
        $this->view->assign('type', $type);
        return $this->view->fetch();
    }

    /**
     * 批量下载图片
     */
    public function downloadImages()
    {
        $ids = $this->request->post('ids');
        $type = $this->request->post('type', 'report');
        
        if (!$ids) {
            $this->error('请选择要下载的图片');
        }
        
        $idsArr = is_array($ids) ? $ids : explode(',', $ids);
        
        if ($type == 'report') {
            $images = \app\admin\model\scanwork\ItemReportImage::where('id', 'in', $idsArr)->select();
        } else {
            $images = \app\admin\model\scanwork\ItemAuditImage::where('id', 'in', $idsArr)->select();
        }
        
        if (empty($images)) {
            $this->error('未找到图片');
        }
        
        // 创建临时目录
        $tempDir = ROOT_PATH . 'runtime/temp/images_' . time() . '/';
        if (!is_dir($tempDir)) {
            mkdir($tempDir, 0777, true);
        }
        
        $zipFile = $tempDir . 'images.zip';
        $zip = new \ZipArchive();
        $zip->open($zipFile, \ZipArchive::CREATE);
        
        foreach ($images as $image) {
            $sourceFile = ROOT_PATH . 'public' . $image->image_url;
            if (file_exists($sourceFile)) {
                $filename = basename($image->image_url);
                $zip->addFile($sourceFile, $filename);
            }
        }
        
        $zip->close();
        
        // 下载文件
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="images.zip"');
        header('Content-Length: ' . filesize($zipFile));
        readfile($zipFile);
        
        // 删除临时文件
        unlink($zipFile);
        rmdir($tempDir);
        exit;
    }
} 